package com.roc.web.action.merinfo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.dao.DaoException;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.pojo.TblMerAgentRelation;
import com.roc.service.ServiceException;
import com.roc.service.operator.IPowerInfoService;
import com.roc.service.profit.IProfitService;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;

@Component
@Namespace("/mer") 
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class MerchantBelongAction extends PaginationBaseAction{
	private static Logger logger = Logger.getLogger(MerchantBelongAction.class);
	
	private MerchantBelongSearchCondition searchCondition;
	@Autowired
	IProfitService profitService;
	@Autowired
	private IPageService pagenitionService;
	@Autowired
	IPowerInfoService iPowerInfoService;
	
	private String[] roleArray = { Role.SYSTEM.getCode(),
			Role.MANAGER.getCode(), Role.O_MANAGER.getCode(),
			Role.AGENT.getCode(), Role.CLEAR_OPERATORS.getCode(),
			Role.CLEAR_LEAD.getCode(), Role.FINANCE_COMM.getCode(),
			Role.FINANCE_LEAD.getCode(), Role.OPERATORS_COMM.getCode(),
			Role.OPERATORS_LEAD.getCode(),
			Role.RISK_CONTROL_OPERATORS.getCode(),
			Role.RISK_CONTROL_LEAD.getCode(),
			Role.WARE_HOUSE_LEAD.getCode() };
	
	@Action(value = "queryMerAgentRelaJsp", results = { @Result(name = "success", location = "/pages/merinfo/merAgentRelaJsp.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryMerAgentRelaJsp(){
		try {
			Operators op = (Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			 /*if(op.getRoleType().equals(Role.AGENT.getCode()) && !op.getAccountNo().equals("sdsyb")){
				 addActionError("无权限访问");
				 return ERROR;
			 }*/
			
			
			boolean roleFlag = false;
			for(int i =0 ;i<roleArray.length;i++){
				if(roleArray[i].equals(op.getRoleType())){
					roleFlag = true;
					break;
				}
			}
			
			if(!roleFlag){
				addActionError("无权限访问");
				return ERROR;
			}
			
		} catch (Exception e) {
			logger.error("查询商户所属代理商页面初始化异常", e);
			addActionError("查询商户所属代理商页面初始化异常");
		}
		return SUCCESS;
	}
	
	@Action(value = "queryMerBelongList", results = { @Result(name = "success", location = "/pages/merinfo/merAgentRelaJsp.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryMerBelongList() throws DaoException{
		Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
		
		boolean roleFlag = false;
		for(int i =0 ;i<roleArray.length;i++){
			if(roleArray[i].equals(logingMerchant.getRoleType())){
				roleFlag = true;
				break;
			}
		}
		
		if(!roleFlag){
			addActionError("无权限访问");
			return ERROR;
		}
		
		if(searchCondition == null){
			searchCondition = (MerchantBelongSearchCondition) getSearchConditionFromSession();
			if(searchCondition == null){
				searchCondition = new MerchantBelongSearchCondition();
			}
		}
		
		try {
			//运营角色转换
			Map<String, String> map=iPowerInfoService.queryRealIdByOpId(logingMerchant.getSuperiorId(), logingMerchant.getRoleType(), logingMerchant.getId(), logingMerchant.getOrgCode());
//            String orgCode=map.get("orgCode");
            String superRole= map.get("superRole");
            String opRealId =map.get("opRealId");

            searchCondition.setRoleType(superRole);
            //运营 代理商 机构管理员 
			if(Role.AGENT.getCode().equals(superRole) || Role.O_MANAGER.getCode().equals(superRole)){
				
				searchCondition.setAgentId(opRealId);
				
			}else{
				searchCondition.setOrgCode(logingMerchant.getOrgCode());
			}
			
			int rows = pagenitionService.countSQL(searchCondition);
			if(rows>0){
				searchRsList = pagenitionService.findAllSQL(searchCondition, calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
			}
			List<TblMerAgentRelation> resList = new ArrayList<TblMerAgentRelation>();
			dealTheListSpecial(searchRsList,resList,logingMerchant);
			
			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, resList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (ServiceException e) {
			logger.error("商户所属机构查询异常");
		}
		return SUCCESS;
	}

	private void dealTheListSpecial(List<Object> searchRsList, List<TblMerAgentRelation> resList,Operators logingMerchant) {
		if(searchRsList != null && searchRsList.size()>0){
			Iterator<Object> it = searchRsList.iterator();
			while(it.hasNext()){
				Object[] obj = (Object[]) it.next();
				TblMerAgentRelation t = new TblMerAgentRelation();
				t.setAgentId(Long.parseLong(Constance.Null2EmptyTrim(obj[0])));
				t.setMerno(Constance.Null2EmptyTrim(obj[1]));
				//t.setCreateDate(Constance.Null2EmptyTrim(obj[2]));
				t.setMerName(Constance.Null2EmptyTrim(obj[2]));
				t.setAgentName(Constance.Null2EmptyTrim(obj[3]));
				t.setInsNo(Constance.Null2EmptyTrim(obj[4]));
				if(Role.AGENT.getCode().equals(logingMerchant.getRoleType()) && !"sdsyb".equals(logingMerchant.getAccountNo())){
					t.setAgentTel(Utils.dealMobile(Constance.Null2EmptyTrim(obj[5])));
				}else{
					t.setAgentTel(Constance.Null2EmptyTrim(obj[5]));
				}
				
				resList.add(t);
			}
		}
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {
		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
		
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_MERCHANT_AGENT_RELA, searchCondition);
		
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {
		return (MerchantBelongSearchCondition) getSession().getAttribute(SEARCH_SESSION_MERCHANT_AGENT_RELA);
	}

	@Override
	protected String getInitPageSize() {
		return Constance.PAGE_MAX_SIZE + "";
	}

	public MerchantBelongSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(MerchantBelongSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}
	 
	
}
